/* eslint-disable no-plusplus */
/* eslint-disable no-param-reassign */
export function convertTreeData(
  result: Record<string, any>[],
  parentCode: string,
  code: string,
  func?: (arg: any) => any,
  rootCode?: string | number,
) {
  const dict = Object.create(null);
  for (let i = 0, len = result.length; i < len; i++) {
    const pareCode = result[i][parentCode];
    if (!dict[pareCode]) dict[pareCode] = [];
    dict[pareCode].push(result[i]);
  }
  const getChildren = (arr: Record<string, any>[]) => {
    for (let i = 0, len = arr.length; i < len; i++) {
      if (func) arr[i] = { ...arr[i], ...func(arr[i]) };
      const getList = dict[arr[i][code]];
      if (getList) {
        arr[i] = { ...arr[i], children: getList };
        getChildren(arr[i].children);
      }
    }
  };

  const parent = rootCode ? dict[rootCode] : dict['0'];
  getChildren(parent);
  return parent;
}
